#!/bin/sh

DEFAULT_EXPANDABLE_STORAGE_CLASSNAME="expandable-sc"

init_expandable_storage_class(){
  EXPANDABLE_STORAGE_CLASSNAME="$(get_expandable_storage_class_configured)"

  if [ -n "$EXPANDABLE_STORAGE_CLASSNAME" ]
  then
    echo "Expandable storage class already configured, skipping initialization."
  else
    echo "No expandandable storage class detected, creating one."
    if ! command -v create_expandable_storage_class_k8s >/dev/null 2>&1
    then
      echo "There is no environment specific function to create expandable storage class, generating one from default."
      EXPANDABLE_STORAGE_CLASSNAME="$(create_expandable_storage_class_from_default)"
    else
      echo "There is no environment specific expandable storage class."
      EXPANDABLE_STORAGE_CLASSNAME="$(create_expandable_storage_class_k8s)"
    fi 
  fi
}

get_expandable_storage_class_configured(){
  local EXPANDABLE_STORAGE_CLASSNAME

  if command -v get_expandable_storage_class_name >/dev/null 2>&1
  then 
    get_expandable_storage_class_name
  else
    get_first_expandable_storage_class_name
  fi
}

create_expandable_storage_class_from_default(){
  local DEFAULT_STORAGE_CLASSNAME
  DEFAULT_STORAGE_CLASSNAME="$(get_default_storage_class_name)"
  command -v generate_storage_class_from_default
  generate_storage_class_from_default \
    "$DEFAULT_STORAGE_CLASSNAME" \
    "$DEFAULT_EXPANDABLE_STORAGE_CLASSNAME" \
    | kubectl apply -f - > /dev/null
  printf '%s' "$DEFAULT_EXPANDABLE_STORAGE_CLASSNAME"
}

generate_expandable_storage_class_from(){
  local SOURCE_STORAGE_CLASSNAME="$1"
  local TARGET_STORAGE_CLASSNAME="$2"
  kubectl get storageclasses.storage.k8s.io "$SOURCE_STORAGE_CLASSNAME" -o json \
     | jq 'del(.metadata)' | jq '.metadata= {}' | jq '.metadata.name = "'"$TARGET_STORAGE_CLASSNAME"'"' \
     | jq '.allowVolumeExpansion = "true"'
}

get_default_storage_class_name() {
  kubectl get storageclasses.storage.k8s.io -o json \
    | jq -r '.items | map(select(.metadata.annotations."storageclass.kubernetes.io/is-default-class" == "true"))
      | map(.metadata.name) | first | select (.!=null)'
}

get_first_expandable_storage_class_name() {
  kubectl get storageclasses.storage.k8s.io -o json \
    | jq -r '.items | map(select(.allowVolumeExpansion == true))
      | map(.metadata.name) | first | select (.!=null)'
}
